﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using DapperHelper.Attributes;

namespace DapperHelper.SqlBuilder
{
    public abstract class AbstractSqlBuilder<T> : ISqlBuilder<T>
    {
        protected IList<PropertyInfo> AllField { get; private set; }
        
        protected StringBuilder SqlBuilder { get; }

        protected AbstractSqlBuilder()
        {
            InitAllFieldName();
            SqlBuilder = new StringBuilder();
        }

        public Type GetObjectType()
        {
            return typeof(T);
        }

        public string TableName()
        {
            Type t = GetObjectType();
            TableAttribute attr = t.GetCustomAttribute<TableAttribute>();
            if (attr == null)
            {
                return t.Name;
            }

            return attr.TableName;
        }

        public void InitAllFieldName()
        {
            if (AllField is null)
            {
                AllField = new List<PropertyInfo>();
                Type t = GetObjectType();
                foreach (var prop in t.GetProperties())
                {
                    string fieldName = FieldName(prop);
                    if (string.IsNullOrEmpty(fieldName))
                    {
                        continue;
                    }

                    AllField.Add(prop);
                }
            }
            
        }

        public string FieldName(PropertyInfo prop)
        {
            IgnoreFieldAttribute ig = prop.GetCustomAttribute<IgnoreFieldAttribute>();
            if (ig != null)
            {
                return string.Empty;
            }

            SqlFieldAttribute field = prop.GetCustomAttribute<SqlFieldAttribute>();
            return field == null ? prop.Name : field.FieldName;
        }

        public virtual string Build()
        {
            return SqlBuilder.ToString();
        }
    }
}